﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Collections.ObjectModel;
using BAL.EstRec;
using MasterDetailEx;
using Microsoft.Win32;
using BAL.EstRec.FDVIndicador;


namespace Nav3
{
    /// <summary>
    /// Lógica de interacción para CapturaFDV.xaml
    /// </summary>
    public partial class CapturaFDV : UserControl, InterfazControl, ISave
    {
        public string unidVersion = "";
        public string auxVersion = "";
        public string aux2Version = "";
        public List<CapturaFdv> lisFDV;
        public List<Pos> llenaComboPos;
        public List<Recurso> llenaComboRecurso;
        public string pos;
        public string idPos;
        public string recurso;
        public string idRecurso;
        public TagCreateControl eaux;
        public TagCreateControl eaux2;
        public TagCreateControl ea;
        private FdvVersion currentFdvVersion;

        public bool IsModified { get; set; }
        public string currentPositionCode { get; set; }

        string ExcelOGrid = "Excel";

        public void setUnidVersion(long version)
        {
            this.currentFdvVersion = FdvVersion.GetFdvVersionByUnid(version);
            if (this.currentFdvVersion != null)
            {
                if (this.currentFdvVersion.DatePublished != DateTime.MinValue)
                {
                    this.lblStatus.Content = "Versión Publicada";
                    this.btnPegar.IsEnabled = false;
                    this.btnGuardar.IsEnabled = false;
                    this.cBPos.IsEnabled = false;
                    this.cBRecurso.IsEnabled = false;
                    this.txtCantidad.IsEnabled = false;
                    this.dataGridFDV.IsReadOnly = true;
                    this.cBRecurso.Text = "";
                    this.cBPos.Text = "";
                    this.txtCantidad.Text = "";


                }
                else
                {
                    this.lblStatus.Content = "";
                    this.btnPegar.IsEnabled = true;
                    this.btnGuardar.IsEnabled = true;
                    this.cBPos.IsEnabled = true;
                    this.cBRecurso.IsEnabled = true;
                    this.txtCantidad.IsEnabled = true;
                    this.dataGridFDV.IsReadOnly = false;
                    this.cBRecurso.Text = "";
                    this.cBPos.Text = "";
                    this.txtCantidad.Text = "";
                }

                if (this.currentFdvVersion.HqDateClosed != DateTime.MinValue)
                {
                    this.lblStatus.Content = "Versión Cerrada";
                    this.btnPegar.IsEnabled = false;
                    this.btnGuardar.IsEnabled = false;
                    this.cBPos.IsEnabled = false;
                    this.cBRecurso.IsEnabled = false;
                    this.txtCantidad.IsEnabled = false;
                    this.dataGridFDV.IsReadOnly = true;
                    this.cBRecurso.Text = "";
                    this.cBPos.Text = "";
                    this.txtCantidad.Text = "";
                }
            }
        }

        public void setVersion(string unidVersion, TagCreateControl e)
        {
            if (this.unidVersion == "")
            {
                this.unidVersion = unidVersion;
                ea = e;
            }
            else if (this.unidVersion != unidVersion)
            {
                this.auxVersion = this.unidVersion;
                this.unidVersion = unidVersion;

                eaux = ea;
                ea = e;

            }
            else
            {
                this.unidVersion = unidVersion;
                ea = e;
            }

            if (unidVersion != "")
            {
                setUnidVersion(long.Parse(unidVersion));

                if (IsModified)
                {
                    var result = MessageBox.Show("¿Desea guardar los cambios antes de salir?", "Mensaje del Sistema", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        //llamamos a la funcion que actualiza o inserta a la base
                        this.unidVersion = this.auxVersion;
                        save();

                        IsModified = false;
                        this.unidVersion = unidVersion;
                        loadData();
                    }
                    else if (result == MessageBoxResult.No)
                    {
                        //actualizamos la coleccion

                        IsModified = false;

                        loadData();
                    }
                    else
                    {
                        //guardar la version anterior

                        this.aux2Version = this.auxVersion;

                        this.auxVersion = this.unidVersion;

                        eaux2 = eaux;

                        eaux = e;

                        IsModified = false;

                        loadData();

                    }

                }
                else
                {
                    loadData();
                }
            }
        }

        public CapturaFDV()
        {
            InitializeComponent();

            lisFDV = new List<CapturaFdv>();

            unidVersion = "";
        }

        public void LlenarCombos()
        {

            llenaComboPos = BAL.EstRec.Pos.GetComboPos2(currentPositionCode);
            cBPos.ItemsSource = llenaComboPos;

            llenaComboRecurso = BAL.EstRec.Recurso.GetComboRecurso2(currentPositionCode);
            cBRecurso.ItemsSource = llenaComboRecurso;
        }

        private void btnPegar_Click(object sender, RoutedEventArgs e)
        {
            if (!unidVersion.Equals(""))
            {

                DialogGeneraGridExel2 ge = new DialogGeneraGridExel2();

                try
                {
                    IDataObject data = Clipboard.GetDataObject();
                    if (data.GetDataPresent(DataFormats.Text))
                    {
                        string tmp = (String)data.GetData(DataFormats.Text);
                        string aux = "";
                        aux = tmp.Trim();
                        if (aux.Equals(""))
                        {

                            ge.Close();
                            MessageBox.Show("No ha copiado nada de excel.", "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        else
                        {
                            ge.setVersion(unidVersion);
                            ge.setCurrentPosition(currentPositionCode);
                            ge.convertirExcelAGrid(tmp);
                            ge.rfdv = this;
                            ge.Show();
                        }
                    }
                }
                catch (Exception Ex)
                {
                    ge.Close();
                    MessageBox.Show("El formato de los datos no coincide.", "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {

                MessageBox.Show("Seleccione una versión.", "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        public void InformacionDeExcel(DataTable dt)
        {
            IsModified = true;

            string dd1 = "";
            string dd2 = "";
            string dd3 = "";
            string dd4 = "";
            string dd5 = "";
            string dd6 = "";
            string dd7 = "";

            int col = 0;

            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    if (col == 0)
                        dd1 = dr.ItemArray[col].ToString();
                    if (col == 1)
                        dd3 = dr.ItemArray[col].ToString();
                    if (col == 2)
                        dd2 = dr.ItemArray[col].ToString();
                    if (col == 3)
                        dd5 = dr.ItemArray[col].ToString();
                    if (col == 4)
                        dd4 = dr.ItemArray[col].ToString();
                    if (col == 5)
                        dd6 = dr.ItemArray[col].ToString();
                    if (col == 6)
                        dd7 = dr.ItemArray[col].ToString();

                    col += 1;
                }

                if (validarRepetido(dd2, dd4, Int32.Parse(dd6)) == true)
                {
                    IsModified = true;

                    //actualizamos
                    //(from hq in lisFDV
                    // where hq.idPos == dd2 && hq.idRecurso == dd4
                    // select hq).ToList<CapturaFdv>().ForEach(hq => hq.Cantidad = Int32.Parse(dd6));
                    //this.dataGridFDV.DataContext = this.lisFDV;
                    //this.dataGridFDV.Items.Refresh();




                    //actualizamos
                    var list = ((OCViemModelFDV)this.DataContext).collections;
                    //(from hq in lisHQ
                    (from hq in list
                     where hq.POS == dd3 && hq.Recurso == dd5
                     select hq).ToList<CapturaFdv>().ForEach(hq => hq.Cantidad = Int32.Parse(dd6));



                }
                else
                {
                    var res = (from hq in llenaComboPos
                               where hq.pos == dd3
                               select hq.idPos);

                    foreach (var r in res)
                    {
                        dd2 = r;
                    }

                    var res2 = (from hq in llenaComboRecurso
                                where hq.recurso == dd5
                                select hq.idRecurso);

                    foreach (var r in res2)
                    {
                        dd4 = r.ToString();
                    }

                    dd1 = unidVersion;
                    if (validarRepetido(dd2, dd4, Int32.Parse(dd6)) == true)
                    {
                        IsModified = true;
                        //Actualizamos
                        //(from hq in lisFDV
                        // where hq.idPos == dd2 && hq.idRecurso == dd4
                        // select hq).ToList<CapturaFdv>().ForEach(hq => hq.Cantidad = Int32.Parse(dd6));
                        //this.dataGridFDV.DataContext = this.lisFDV;
                        //this.dataGridFDV.Items.Refresh();





                        //Actualizamos                                               
                        var list = ((OCViemModelFDV)this.DataContext).collections;
                        (from hq in list
                         where hq.POS == dd3 && hq.Recurso == dd5
                         select hq).ToList<CapturaFdv>().ForEach(hq => hq.Cantidad = Int32.Parse(dd6));





                    }
                    else
                    {
                        IsModified = true;
                        //insertamos
                        this.lisFDV.Add(new CapturaFdv(long.Parse(dd1), dd2, dd3, dd4, dd5, Int32.Parse(dd6)));
                        this.dataGridFDV.DataContext = this.lisFDV;
                        this.dataGridFDV.Items.Refresh();
                    }
                }

                col = 0;
            }
        }

        private void btnExportarXLS_Click(object sender, RoutedEventArgs e)
        {

        }

        private void cBPos_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void cBRecurso_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void dataGridFDV_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.currentFdvVersion.DatePublished == DateTime.MinValue && this.currentFdvVersion.HqDateClosed == DateTime.MinValue)
            {
                if (sender != null)
                {
                    DataGrid grid = sender as DataGrid;
                    if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                    {

                        DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;

                        //combo pos
                        this.cBPos.SelectedItem = new Pos(((BAL.EstRec.CapturaFdv)grid.SelectedItem).idPos, ((BAL.EstRec.CapturaFdv)grid.SelectedItem).POS);
                        this.cBPos.Text = ((BAL.EstRec.CapturaFdv)grid.SelectedItem).POS;

                        //combo recurso
                        this.cBRecurso.SelectedItem = new Recurso(((BAL.EstRec.CapturaFdv)grid.SelectedItem).idRecurso.ToString(), ((BAL.EstRec.CapturaFdv)grid.SelectedItem).Recurso);
                        this.cBRecurso.Text = ((BAL.EstRec.CapturaFdv)grid.SelectedItem).Recurso;

                        //textbox cantidad
                        this.txtCantidad.Text = ((BAL.EstRec.CapturaFdv)grid.SelectedItem).Cantidad.ToString();

                        this.IsModified = true;

                        this.txtCantidad.Focusable = true;
                        this.txtCantidad.Focus();
                    }
                }
            }
        }

        private void validar()
        {

            //validacion si no hay una version
            if (unidVersion.Equals(""))
            {
                MessageBoxResult result = MessageBox.Show("Selecione una versión", "Mesaje del sistema", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            else
            {
                //validacion si no a seleccionado combo pos, recurso y a escrito texto cantidad
                if (!cBPos.Text.Equals("") && !cBRecurso.Text.Equals("") && !txtCantidad.Text.Equals(""))
                {
                    lblMsgError.Visibility = Visibility.Hidden;
                    //Validar que lo introducido por el usuario sea igual al selected item pos

                    if (validarSelectItemPos() == true)
                    {
                        lblMsgError.Visibility = Visibility.Hidden;
                        idPos = ((Pos)this.cBPos.SelectedItem).idPos.ToString();
                        //Validar que lo introducido por el usuario sea igual al selected item recurso

                        if (validarSelectItemRecurso() == true)
                        {
                            lblMsgError.Visibility = Visibility.Hidden;
                            idRecurso = ((Recurso)this.cBRecurso.SelectedItem).idRecurso.ToString();
                            //valida que txtCantidad sea numerico
                            if (validaCantidad(txtCantidad.Text) == true)
                            {
                                lblMsgError.Visibility = Visibility.Hidden;
                                //Validar que no se agregue un elemento ya repetido
                                if (validarRepetido(idPos, idRecurso, Int32.Parse(txtCantidad.Text)) == true)
                                {

                                    //actualizamos
                                    var list = ((OCViemModelFDV)this.DataContext).collections;
                                    (from hq in list
                                     where hq.idPos == idPos && hq.idRecurso == idRecurso
                                     select hq).ToList<CapturaFdv>().ForEach(hq => hq.Cantidad = Int32.Parse(txtCantidad.Text));

                                    IsModified = true;

                                }
                                else
                                {
                                    lblMsgError.Visibility = Visibility.Visible;
                                    lblMsgError.Content = "Ingrese una combinación de POS y Recurso adecuada.";

                                }
                            }
                            else
                            {
                                lblMsgError.Visibility = Visibility.Visible;
                                lblMsgError.Content = "Ingrese un número entero en cantidad.";
                            }

                        }
                        else
                        {
                            lblMsgError.Visibility = Visibility.Visible;
                            lblMsgError.Content = "Ingrese un Recurso que exista ...";
                        }
                    }
                    else
                    {
                        lblMsgError.Visibility = Visibility.Visible;
                        lblMsgError.Content = "Ingrese un POS que exista ...";
                    }
                }
                else
                {
                    lblMsgError.Visibility = Visibility.Visible;
                    lblMsgError.Content = "Se deben de ingresar los 3 campos ...";
                }
            }
        }
        private Boolean validarRepetido(string idPos, string idRecurso, int cantidad)
        {
            bool bandera = true;
            var list = ((OCViemModelFDV)this.DataContext).collections;
            int count = (from hq in list
                         where hq.idPos == idPos && hq.idRecurso == idRecurso
                         select hq).Count();

            if (count > 0)
            {
                bandera = true;
            }
            else
            {
                bandera = false;
            }
            return bandera;

        }
        private Boolean validarSelectItemPos()
        {
            bool bandera = true;
            if (this.cBPos.SelectedItem != null)
            {
                if (((Pos)this.cBPos.SelectedItem).pos.ToString() == cBPos.Text)
                {
                    bandera = true;
                }
                else
                {
                    bandera = false;
                }

            }
            else
            {
                bandera = false;
            }
            return bandera;
        }
        private Boolean validarSelectItemRecurso()
        {
            bool bandera = true;
            if (this.cBRecurso.SelectedItem != null)
            {
                if (((Recurso)this.cBRecurso.SelectedItem).recurso.ToString() == cBRecurso.Text)
                {
                    bandera = true;
                }
                else
                {
                    bandera = false;
                }

            }
            else
            {
                bandera = false;
            }
            return bandera;
        }
        private void txtCantidad_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                validar();
            }
        }
        private Boolean validaCantidad(string sCantidad)
        {
            try
            {
                int num = 0;
                num = Int32.Parse(sCantidad);
                return true;
            }
            catch (Exception Ex)
            {
                return false;
            }
        }

        private void btnExportarXLS_Click_1(object sender, RoutedEventArgs e)
        {


            try
            {
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel|*.xlsx";

                if (saveDialog.ShowDialog().Value)
                {
                    this.disableMouseUI();
                    ExportExcel EE = new ExportExcel(saveDialog.FileName, true, unidVersion, currentPositionCode);
                    EE.exportFDV();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo crear el archivo. \nDetalles : " + ex.Message, "Exportar XLS", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            this.enableMouseUI();

        }

        private void btnGuardar_Click_1(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.unidVersion))
                return;

            //preguntar si desea guardar los cambios
            if (MessageBox.Show("¿Desea guardar los cambios?", "Confirmación", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                //llamamos a la funcion que actualiza o inserta a la base
                this.save();

                //hace refresh al grid

                this.loadData();

                //activa la bandera cuando se guarda 
                this.IsModified = false;
            }
            else
            {
                this.IsModified = false;
            }
        }

        public void save()
        {
            if (!String.IsNullOrEmpty(this.unidVersion) && ((OCViemModelFDV)this.DataContext) != null)
            {
                try
                {
                    //CapturaFdv hq;
                    var list = ((OCViemModelFDV)this.DataContext).collections;
                    var res = (from o in list
                               where o.IsModified == true
                               select new VMCapturaPivotFDV(new Pos(o.POS, ""), new Recurso(o.Recurso, ""), o.cantidad) { IsModified = o.IsModified }).ToList(); ;
                    CollectionsPivotFDV colPfdv = new CollectionsPivotFDV(res);

                    ViewModelSaveCapFdv vm = new ViewModelSaveCapFdv(colPfdv, Convert.ToInt64(this.unidVersion));
                    DlgSave ds = new DlgSave();
                    ds.DataContext = vm;
                    try
                    {
                        ds.Owner = Application.Current.Windows[0];
                    }
                    catch (Exception ex)
                    {
                        ;
                    }
                    vm.start();
                    ds.ShowDialog();

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show("Problema al guardar. "+ex.Message,"Captura FDV", MessageBoxButton.OK,MessageBoxImage.Error);
                }

                //guradamos los unidhq que esten null en la base de datos
                //foreach (var item in lisFDV)
                //{
                //    if (item.unidHqBgt == 0)
                //    {
                //        //insertamos a la base de datos
                //        hq = new CapturaFdv(item.unidHqBgtVersion, item.idPos, item.POS, item.idRecurso, item.Recurso, item.Cantidad);
                //        CapturaFdv.InsertUpdateCapturaFDV(hq);
                //    }
                //    else
                //    {
                //        //actualizamos a la base de datos
                //        hq = new CapturaFdv(item.unidHqBgtVersion, item.idPos, item.POS, item.idRecurso, item.Recurso, item.Cantidad);
                //        CapturaFdv.InsertUpdateCapturaFDV(hq);
                //    }
                //} 
            }
            else
            {
                MessageBox.Show("No existe una versión seleccionada o no hay información para guardar.", "Captura Rápida", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
        public void loadData()
        {
            //lisFDV = CapturaFdv.GetCapturaFDV(Convert.ToInt64(unidVersion));

            //this.DataContext = new OCViemModelFDV(lisFDV);

            //this.dataGridFDV.ItemsSource = ((OCViemModelFDV)this.DataContext).collections;
            this.LlenarCombos();
            if (auxVersion != this.unidVersion)
            {

                lisFDV = CapturaFdv.GetCapturaFDV(Convert.ToInt64(this.unidVersion));

                this.DataContext = new OCViemModelFDV(lisFDV);

                this.dataGridFDV.ItemsSource = ((OCViemModelFDV)this.DataContext).collections;

            }
            else //(auxVersion == unidVrs)  
            {
                if (aux2Version == "")
                {
                    if (!String.IsNullOrEmpty(this.auxVersion))
                    {
                        lisFDV = CapturaFdv.GetCapturaFDV(Convert.ToInt64(this.auxVersion));

                        this.DataContext = new OCViemModelFDV(lisFDV);

                        this.dataGridFDV.ItemsSource = ((OCViemModelFDV)this.DataContext).collections;
                    }

                }
                else
                {
                    eaux2.RaiseClickEvent();

                    lisFDV = CapturaFdv.GetCapturaFDV(Convert.ToInt64(this.aux2Version));

                    this.DataContext = new OCViemModelFDV(lisFDV);

                    this.dataGridFDV.ItemsSource = ((OCViemModelFDV)this.DataContext).collections;
                }
            }
        }

        private void disableMouseUI()
        {
            this.IsHitTestVisible = false;
            Mouse.OverrideCursor = Cursors.Wait;
        }

        private void enableMouseUI()
        {
            this.IsHitTestVisible = true;
            Mouse.OverrideCursor = Cursors.Arrow;
        }
    }
}
